<%--
  -	Date: 2012-05-25
  -
  - Copyright (C) 2012 Jawa Software. All rights reserved.
  - 
  - 创建新部门页面。
--%>
<%@ page language="java" pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c"%>
<%@ page import="org.jawa.admin.util.ParamUtils,org.jawa.core.util.JawaGlobals,org.jawa.core.JawaServer,org.jawa.branch.*,org.jawa.core.database.SequenceManager,org.jawa.core.util.JawaConstants"
%>
<%@ page import="java.util.Collection,
                 java.util.List,
                 java.util.ArrayList,
                 java.util.Map,
                 java.util.HashMap,
                 java.net.URLEncoder"
%>
<%@ page import="org.apache.commons.lang.StringUtils"%>
<jsp:useBean id="webManager" class="org.jawa.admin.util.WebManager"  />
<% 
    webManager.init(request, response, session, application, out);
	String path = request.getContextPath();
%>

<%
	Map<String,String> errors = new HashMap<String,String>();
	boolean success;
	
	boolean edit = request.getParameter("edit") != null;
	boolean create = request.getParameter("create") != null;
	boolean update = request.getParameter("update") != null;
	boolean delete = request.getParameter("delete") != null;
	
	Long brId = ParamUtils.getLongParameter(request,"brId",-1L);
	Branch branch = null;
	if(edit){
		try{
			branch = BranchManager.getInstance().getBranch(brId);
		}catch(Exception ex){
			//忽略
		}
	}
	if(null==branch){
		branch = new Branch();
	}
	
	if (delete)
	{
		BranchManager.getInstance().deleteBranch(brId);
		success = true;
		response.sendRedirect("index.jsp?delete=true&success=true");
        return;
	}
	
	
	//创建部门
	if (create)
	{
		String brNo = ParamUtils.getParameter(request,"brNo");
		String brName = ParamUtils.getParameter(request,"brName");
		String brStatus = ParamUtils.getParameter(request,"brStatus");
		String brParentId = ParamUtils.getParameter(request,"brParentId");

		if(StringUtils.isEmpty(brNo)){
			errors.put("brNo","");
		}
		if(StringUtils.isEmpty(brName)){
			errors.put("brName","");
		}
		if(StringUtils.isEmpty(brStatus)){
			errors.put("brStatus","");
		}
		
		
		if(errors.isEmpty()){
			branch = new Branch();
			branch.setBrNo(brNo);
			branch.setBrName(brName);
			branch.setBrStatus(brStatus);
			if(StringUtils.isNotEmpty(brParentId)){
				branch.setBrParentId(Long.valueOf(brParentId));
			}
			try{
				Long nextBranchId = SequenceManager.nextID(JawaConstants.DB_BRANCH_SEQ);
				branch.setBrId(nextBranchId);
				BranchManager.getInstance().createBranch(branch);
				success = true;
			}catch(Exception ex){
				success = false;
				errors.put("general","");
			}
			
			if(success){
	            response.sendRedirect("index.jsp?create=true&success=true");
	            return;
			}
			
		}
	}
	
	//更新部门
	if (update)
	{
		String brNo = ParamUtils.getParameter(request,"brNo");
		String brName = ParamUtils.getParameter(request,"brName");
		String brStatus = ParamUtils.getParameter(request,"brStatus");
		String brParentId = ParamUtils.getParameter(request,"brParentId");
		
		if(StringUtils.isEmpty(brNo)){
			errors.put("brNo","");
		}
		if(StringUtils.isEmpty(brName)){
			errors.put("brName","");
		}
		if(StringUtils.isEmpty(brStatus)){
			errors.put("brStatus","");
		}
		
		if(errors.isEmpty()){
			try{
				BranchManager.getInstance().updateBranch(brId,brNo,brName,brStatus,brParentId);
				success = true;
			}catch(Exception ex){
				success = false;
				errors.put("general","");
			}
			
			if(success){
	            response.sendRedirect("index.jsp?update=true&success=true");
	            return;
			}
			
		}
	}

%>
<!DOCTYPE html>
<html lang="en">
	<head>
		<title>编辑部门</title>
		<meta name="pageID" content="1201" />
		<link rel="stylesheet"  href="<%= path %>/styles/ztree/ztree.css">
	</head>
	<body>
		<div class="row-fluid">

			<ul class="breadcrumb">
				<li>
					您现在的位置:
				</li>
				<li>
					<a href="<%=path%>/admin/index.jsp">系统管理</a>
				</li>
				<li>
					<span class="divider">/</span>
				</li>
				<li>
					<a href="<%=path%>/admin/user/index.jsp">部门管理</a>
				</li>
				<li>
					<span class="divider">/</span>
				</li>
				<li class="active">
					<%
						if(edit){
					%>
						修改部门
					<%		
							
						}else{
					%>
						创建新部门
					<%		
						}
					%>
				</li>
			</ul>
			<%
				if(errors.get("general")!=null)
				{
					if(edit){
			%>		
				  <div class="alert alert-error fade in">
				    <a class="close" data-dismiss="alert" href="#">×</a>
					<strong>更新部门时发生错误.</strong>
				  </div>			
			<%	
					}else{
			%>		
				  <div class="alert alert-error fade in">
				    <a class="close" data-dismiss="alert" href="#">×</a>
					<strong>创建部门时发生错误,可能是部门编号已存在.</strong>
				  </div>			
			<%	
						
					}
				}
			%>
			<form id="branchForm" action="branch-form.jsp" method="post" class="form-horizontal well">
			    <%
			    	if(edit){
			    %>
			    	<input type="hidden" name="brId" value="<%=branch.getBrId()%>">
			    <%		
			    	}
			    %>
				<fieldset>
					<legend>
						创建部门
					</legend>
					<div class="row-fluid">
							<div class="control-group">
								<label class="control-label">
									上级部门:
								</label>
								<div class="controls">
								    <%
								    	Branch parentBranch = branch.getParent();
								    	String parentbrName = "";
								    	if(null!=parentBranch){
								    		parentbrName = parentBranch.getBrName();
								    	}
								    %>
									<input type="hidden" id="parentBrId" name="brParentId" value="<%=branch.getBrParentId() %>" />
									<input type="text" id="parentBrName" name="parentBrName" value="<%=parentbrName %>" maxlength="15" class="" readonly="readonly" onclick="showMenu(); return false;" style="cursor: pointer;" />
									<%
										if (errors.get("parentBrId") != null) {
									%>
									<span class="help-inline">请选择正确的上级部门</span>
									<%
										}
									%>
								</div>
							</div>
							<div class="control-group">
								<label class="control-label">
									部门编码:
								</label>
								<div class="controls">
									<input type="text" name="brNo" value="<%=StringUtils.trimToEmpty(branch.getBrNo()) %>"  maxlength="15"  class="" />
									<%
										if (errors.get("brNo") != null) {
									%>
									<span class="help-inline">请输入部门编码</span>
									<%
										}
									%>
								</div>
							</div>
							<div class="control-group">
								<label class="control-label">
									部门名称:
								</label>
								<div class="controls">
									<input type="text" name="brName" value="<%=StringUtils.trimToEmpty(branch.getBrName()) %>" maxlength="15"  class="" />
									<%
										if (errors.get("brName") != null) {
									%>
									<span class="help-inline">请输入部门名称</span>
									<%
										}
									%>									
								</div>
							</div>
							<div class="control-group">
								<label class="control-label">
									部门状态:
								</label>
								<div class="controls">
									<select id="brStatus" name="brStatus" >
										<option value="0" <%=StringUtils.equals(branch.getBrStatus(),"0")?"selected=\"selected\"":"" %>>
											正常
										</option>
										<option value="1" <%=StringUtils.equals(branch.getBrStatus(),"1")?"selected=\"selected\"":"" %>>
											失效
										</option>
									</select>
									<%
										if (errors.get("brStatus") != null) {
									%>
									<span class="help-inline">请选择部门状态</span>
									<%
										}
									%>
								</div>
						</div>
					</div>
					<div class="span12">
						<div class=" form-actions">
						    <%
						    	if(edit){
						    %>
						    	<input type="submit" name="update" value="保存部门" class="btn btn-primary"">
						    <%		
						    	}else{
							%>
								<input type="submit" name="create" value="保存部门" class="btn btn-primary" />
							<%							    		
						    	}
						    %>
							<input type="button" name="return" value="返回" class="btn" onclick="window.location.href='index.jsp'" />
						</div>
					</div>
				</fieldset>
			</form>

		<div id="menuContent" class="menuContent" style="display:none; position: absolute;background-color: #EEE;">
			<ul id="branchTree" class="ztree" style="margin-top:0; width:210px;border: 1px solid #DDD; "></ul>
		</div>

		</div>
		<script src="<%= path %>/scripts/bootstrap.js"></script>
		<script src="<%= path %>/scripts/jquery.validate.js"></script>
		<script src="<%= path %>/scripts/global.js"></script>
		<script src="<%= path %>/scripts/jquery.ztree.js"></script>
		<script>

		var zNodes =[
					<%
					List<Branch> branchs = BranchManager.getInstance().getBranchs();
					int i = 0;
					int k = branchs.size();
					for(Branch branchObj : branchs){
						i++;
						String data = "{id:"+branchObj.getBrId()+", name: '"+branchObj.getBrName()+"' ";
						if(branchObj.getBrParentId()!=null){
							data +=",pId:"+branchObj.getBrParentId()+"";
						}
						data +="}";
						if(i!=k){
							data +=",";
						}
						out.println(data);
					}
					%>		     		
			];
			var setting = {
				view: {
					dblClickExpand: false
				},
				data: {
					simpleData: {
						enable: true
					}
				},
				callback: {
					beforeClick: beforeClick,
					onClick: onClick
				}
			};
			
			function beforeClick(treeId, treeNode) {}
			
			function onClick(e, treeId, treeNode) {
				var zTree = $.fn.zTree.getZTreeObj("branchTree"),
				nodes = zTree.getSelectedNodes(),
				v = "";
				k = "";
				nodes.sort(function compare(a,b){return a.id-b.id;});
				for (var i=0, l=nodes.length; i<l; i++) {
					v += nodes[i].name + ",";
					k += nodes[i].id + ",";
				}
				if (v.length > 0 ) v = v.substring(0, v.length-1);
				if (k.length > 0 ) k = k.substring(0, k.length-1);
				var brNameObj = $("#parentBrName");
				brNameObj.attr("value", v);
				var brIdObj = $("#parentBrId");
				brIdObj.attr("value", k);
				$("#menuContent").fadeOut("fast");
			}

			function hideMenu() {
				$("#menuContent").fadeOut("fast");
				$("body").unbind("mousedown", onBodyDown);
			}
			function onBodyDown(event) {
				if (!(event.target.id == "menuContent" || $(event.target).parents("#menuContent").length>0)) {
					hideMenu();
				}
			}
			function showMenu() {
				var cityObj = $("#parentBrName");
				var cityOffset = $("#parentBrName").offset();
				$("#menuContent").css({left:cityOffset.left + "px", top:cityOffset.top + cityObj.outerHeight() + "px"}).slideDown("fast");
				$("body").bind("mousedown", onBodyDown);
			}	
		   $().ready(function() {
				$("#branchForm").validate({
					rules: {
						brNo: {
							required:true,
							minlength:2
						},
					    brName: {
							required:true
						},
						brStatus: {
							required:true
						}
					},
					
					messages: {
					}
				});	

				$.fn.zTree.init($("#branchTree"), setting, zNodes);
						
			});
		</script>
		
	</body>